package com.coocaa.ops.common.core.base.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author bijiahao
 * @date : 2017/12/25.
 * @description 定义获取Spring bean 工具类 需配置【@Component注解】
 */
@Component
public class MyAppContextUtil implements ApplicationContextAware {
    private static ApplicationContext app;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        app = applicationContext;
    }

    public static Object getBean(String name) {
        try {
            Object bean = app.getBean(name);
            return bean;
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        try {
            return app.getBean(name, clazz);
        } catch (BeansException e) {
            e.printStackTrace();
            return null;
        }
    }
}
